import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, Injectable, Scope } from "@nestjs/common";
import { Request, Response } from "express";
import { ResponseUtil } from "../common/utils/response.util";
import { SimpleLoggerService } from "../logs/simple-logger.service";

/**
 * 简化的全局HTTP异常过滤器
 * 统一处理HTTP异常，返回标准格式的错误响应
 *
 * 简化特性：
 * - 使用统一的SimpleLoggerService处理所有日志
 * - 移除复杂的工具类依赖
 * - 保持核心功能的同时大幅简化代码
 */
@Injectable({ scope: Scope.REQUEST })
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly simpleLogger: SimpleLoggerService) {}

  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    let status: number;
    let message: string;
    let errorData: any = null;

    // 解析异常信息
    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();

      if (typeof exceptionResponse === "string") {
        message = exceptionResponse;
      } else if (typeof exceptionResponse === "object" && exceptionResponse !== null) {
        const responseObj = exceptionResponse as any;
        message = responseObj.message || responseObj.error || exception.message;
        errorData = responseObj;
      } else {
        message = exception.message;
      }
    } else if (exception instanceof Error) {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      message = exception.message || "服务器内部错误";
    } else {
      status = HttpStatus.INTERNAL_SERVER_ERROR;
      message = "未知错误";
    }

    // 使用简化的日志服务记录异常
    const requestId = this.simpleLogger.logHttpException(exception, request, status, HttpExceptionFilter.name);

    // 构建错误响应
    let errorResponse;
    switch (status) {
      case HttpStatus.BAD_REQUEST:
        errorResponse = ResponseUtil.error(message, status, errorData);
        break;
      case HttpStatus.UNAUTHORIZED:
        errorResponse = ResponseUtil.unauthorized(message);
        break;
      case HttpStatus.FORBIDDEN:
        errorResponse = ResponseUtil.forbidden(message);
        break;
      case HttpStatus.NOT_FOUND:
        errorResponse = ResponseUtil.notFound(message);
        break;
      case HttpStatus.INTERNAL_SERVER_ERROR:
        errorResponse = ResponseUtil.serverError(message);
        break;
      default:
        errorResponse = ResponseUtil.error(message, status, errorData);
    }

    // 添加请求ID到响应头
    response.setHeader("X-Request-ID", requestId);
    response.status(status).json(errorResponse);
  }
}
